﻿
module Sustainalytics.Accounts.Admin {

    import Common = Sustainalytics.Common;
    import CommonAdmin = Sustainalytics.Common.Admin;
    import Routing = Sustainalytics.Routing;

    interface IAccountDetailsController extends ng.IScope {
        getAccount: any;
        getUsers: any;
        usersList: UsersDto[];
        account: AccountsDto;
        status: any;
        count: any;
        orderby: any;
        reverse: any;
        setOrder: any;
        range: any;
        displayedItems: any;
        allUsersSelected: any;
        checkAllUsers: any;
        resetPassword: any;        
        uncheckAllUsers: any;
        checkSortBy: (column: string, direction: boolean) => boolean;
    }

    class AccountDetailsController {

        private $routeParams: any;

        constructor(
            private $scope: IAccountDetailsController,
            $rootScope,
            RoutingService: Routing.IRoutingService,
            notificationFactory: Common.INotificationFactory,
            staticObjectsAdmin: CommonAdmin.IStaticObjects,
            accountsFactory: AccountsService,
            accountUsersFactory: AccountUsersService) {

            var ctx = this;

            ctx.$routeParams = RoutingService.getRouteParams();

            var accountId = ctx.$routeParams.accountId;
            $scope.getUsers = () => {
                var listOptions = new CommonAdmin.HttpGetOptionsDto();

                // get pager
                var pager: Sustainalytics.Pager.PagerController = $scope['pager'];

                // If pager is not defined then abort execution.
                // Current controller is created before Pager controller.
                if (!pager) {
                    $rootScope.loading = false;
                    return;
                }

                listOptions.skip = pager.pagingOptions.pageSize * (pager.pagingOptions.pageIndex - 1);
                listOptions.take = pager.pagingOptions.pageSize;

                accountUsersFactory.accountUsersGetList(accountId, listOptions, $scope.status)
                    .then(data => {
                    $scope.usersList = data;
                    $scope.count = $scope.usersList.length;
                });

                accountUsersFactory.accountUsersGetCount(accountId, $scope.status)
                    .then(data => {
                    pager.totalItemsCount = data;
                });
            };

            // subscribe to pager events
            $scope.$on('pagerChanged', function (event, pager) {
                // get accounts
                $scope.getUsers();
            });

            $scope.getAccount = () => {
                accountsFactory.accountGet(accountId)
                    .then(accountDto => {
                    $scope.account = accountDto;                    
                });
            };
            $scope.orderby = 'fullName';
            $scope.reverse = false;
            $scope.status = 'Active';
            $scope.usersList = [];
            $scope.allUsersSelected = () => {
                var needsMet: number = 0;
                $scope.usersList.map((item) => {
                    if (item.isSelected)
                        needsMet++;
                });

                //return count;
                //var needsMet = Enumerable.From($scope.usersList)
                //    .Where(x => x.isSelected == true).ToArray();
                return (needsMet === $scope.usersList.length);
            }

            $scope.checkAllUsers = () => {
                var newValue = !$scope.allUsersSelected();
                angular.forEach($scope.usersList,(user) => {
                    user.isSelected = newValue;
                }, null);
            };
            $scope.uncheckAllUsers = () => {
                angular.forEach($scope.usersList,(user) => {
                    user.isSelected = false;
                }, null);
            };
            $scope.resetPassword = () => {
                var listOfIds = new Array();
                for (var i = 0; i < $scope.usersList.length; i++) {
                    if ($scope.usersList[i].isSelected === true)
                        listOfIds.push($scope.usersList[i].id);
                }
                if (confirm("The password will be reset for " + listOfIds.length + (listOfIds.length > 1 ? " users" : " user")
                    + "\n" + "Are you sure that you want to continue?"
                    )) {
                    accountUsersFactory.accountUsersResetPasswords(listOfIds).then(function (result) {
                        alert("The password has been reset for " + listOfIds.length + (listOfIds.length > 1 ? " users" : " user")),
                        $scope.uncheckAllUsers()
                    }, function (reason) {
                            staticObjectsAdmin.errorCallback;
                        });
                }
            }        

            $scope.setOrder = orderby => {
                if (orderby === $scope.orderby) {
                    $scope.reverse = !$scope.reverse;
                }
                $scope.orderby = orderby;
            };
            $scope.checkSortBy = (value, direction) => {
                return $scope.orderby === value && $scope.reverse == direction;
            };

            if (accountId != null) {
                $scope.getAccount();
                $scope.getUsers();
            }
        }
    }


    var mod = angular.module(accountAdminModuleName);

    mod.controller('AccountDetailsController',
        ['$scope', '$rootScope', 'RoutingService', 'notificationFactory', 'staticObjectsAdmin', 'AccountsService', 'AccountUsersService', AccountDetailsController]);
}